package com.twu.biblioteca.presenter;

import com.twu.biblioteca.events.HasEventListener;
import com.twu.biblioteca.events.Listener;
import com.twu.biblioteca.model.users.exceptions.InvalidUsernameException;
import com.twu.biblioteca.model.users.exceptions.UserValidationException;
import com.twu.biblioteca.model.session.Session;
import com.twu.biblioteca.model.session.SessionManager;
import com.twu.biblioteca.model.users.UserManager;
import com.twu.biblioteca.model.users.Username;

/**
 * Created with IntelliJ IDEA.
 * User: cschlumb
 * Date: 09/08/2013
 * Time: 15:48
 * To change this template use File | Settings | File Templates.
 */
public class LoginPresenter implements Presenter{

    public interface Display extends HasEventListener{
        public void prompt();
        public Username getUsername() throws InvalidUsernameException;
        public String getPassword();
        public void successMessage();
        public void failureMessage();
    }

    private final Display view;
    private final UserManager userManager;
    private final SessionManager sessionManager;

    public LoginPresenter(Display view, UserManager userManager, SessionManager sessionManager) {
        this.view = view;
        this.userManager = userManager;
        this.sessionManager = sessionManager;
    }

    @Override
    public void go(Session session) {
        bind(session);
        view.prompt();
    }

    void authenticate(Session session){
        try{
            Username username = view.getUsername();
            String password = view.getPassword();

            userManager.authenticateUser(username, password);
            sessionManager.linkSession(session, username);

            view.successMessage();
        } catch (UserValidationException e) {
            view.failureMessage();
        } catch(InvalidUsernameException e){
            view.failureMessage();
        }
    }

    private void bind(final Session session){
        view.addEventListener(new Listener() {
            @Override
            public void onEvent() {
                authenticate(session);
            }
        });
    }

}
